﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using Tools.Debugging;
using System.Security.Cryptography.X509Certificates;

namespace repliback4.Net.ClientSide {
    public class ClientConnection : AsyncConnection {
        public ClientConnection ( TcpClient client ) : base( client ) { }

        public void SwitchToSecure ( String hostname ) {
            this.sslStream = new SslStream( this.netStream, false, new RemoteCertificateValidationCallback( rcvCallback ) );

            this.sslStream.AuthenticateAsClient( hostname );
            this.stream = this.sslStream;
            Logger.Debug( this, "sslStream Authenticated, A:{0} E:{1} MA:{2}, S:{3}",
                this.sslStream.IsAuthenticated,
                this.sslStream.IsEncrypted,
                this.sslStream.IsMutuallyAuthenticated,
                this.sslStream.IsSigned
                );
        }


        public Boolean TrySwitchToSecure ( String hostname ) {
            try {

                this.SwitchToSecure( hostname );

                return true;
            } catch ( AuthenticationException e ) {
                Logger.Exception( this, "SwitchToSecure: AuthenticationException:", e );
            } catch ( Exception e ) {
                Logger.Exception( this, "SwitchToSecure: Exception:", e );
            }
            return false;
        }



        public bool rcvCallback (
                Object sender,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors
            ) {

            //Logger.Debug( this, "sender:{0}, cert:[{1}], chain:{2}, sslPolicyErrors:{3}",
            //    sender.GetType( ).Name,
            //    certificate.ToString( false ),
            //    chain.ToString( ),
            //    sslPolicyErrors.ToString( )
            //    );
            //bool ret = true;
            return true;
        }
    }
}
